package utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Methods for password hashing
 *
 * @author ZimmE
 */
public class Hash {

    private static final String HEXES = "0123456789abcdef";

    /**
     * Turns clear-text password String into MD5 Hashed String
     *
     * @param password
     * @return String
     */
    public static String md5(String password) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger("MyGrona.error").log(Level.SEVERE, null, ex);
        }
        byte[] hash = md.digest(password.getBytes());
        return getHex(hash);
    }

    /**
     * Turns a
     * <code>byte</code> array to
     * <code>String</code>
     *
     * @param raw
     * @return String
     */
    private static String getHex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}
